let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class 沪深港通历史数据沪股通Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/07日沪深港通/沪深港通历史数据_沪股通/`;
        this.encode = 'UTF-8'
        this.params = {
            pageIndex: 1
        }

        this.pageTotal = 2;

        this.data = []
    }
    /**
     * 获取url
     */
    getUrl(date) {
        return `http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?type=HSGTHIS&token=70f12f2f4f091e459a279469fe49eca5&filter=(MarketType=1)&js=var%20gigSKpjO={%22data%22:(x),%22pages%22:(tp)}&ps=20&p=${this.params.pageIndex}&sr=-1&st=DetailDate&rt=51104025`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('16沪深港通历史数据_沪股通Controller')
        //--------------------
        if (this.params.pageIndex <= this.pageTotal) {
            console.log(JSON.stringify(this.params))
            let result = await this.getData('', this.isCache)
            result = this.axiosDataFormat(result.toString());
            let pageDate = result.data;
            this.pageTotal = result.pages||0
            this.data = [...this.data, ...pageDate]
            this.params.pageIndex++;
            await this.getHistory()
        }
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace('var gigSKpjO=', ''))
        } catch (err) {
            result = eval('(' + data.replace('var gigSKpjO=', '') + ')')
        }
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        if (arr && arr.length) {
            fs.writeFileSync(path.join(this.baseSrc, `沪深港通历史数据_沪股通_${new Date().format('yyyyMMdd')}.csv`), this.convertToCSV(arr, 'title'), 'UTF-8')
        }
    }

    async main(startDate = '2015-01-01', isCache = true) {
    this.startDate = startDate; this.isCache = isCache;
        console.log('--->16沪深港通历史数据_沪股通Controller')
        await this.getHistory()
        this.writeCsv(this.data);
    }
}

let controller = new 沪深港通历史数据沪股通Controller()
module.exports = controller